document.addEventListener('DOMContentLoaded', function () {
  crumbsNav();
  leftTabClick();
  bottomTabClick();
  leftNav();
  leftLeave();
  initSmallPic();
  // slideShow()
  thumbImgClick();
  arrowClick();
  zoomGlass();
  goodsBaseNews();
  goodsSizeNews();
  goodsClick();
  chooseRemove();
  attachGoods();
});

//1、面包屑导航条
function crumbsNav() {
  var date = goodData.path;
  //找父容器
  var conPoinEle = document.querySelector('.wrap .con .conPoin');
  //遍历path
  date.forEach(function (item, index) {
    //创建a节点
    var aNode = document.createElement('a');
    aNode.innerText = item.title;
    // if(index !== date.length -1){
    //   aNode.href = item.url
    // }
    if (item.url) {
      aNode.href = item.url;
    }

    conPoinEle.appendChild(aNode);
  });
}
//2、左侧选项卡切换
function leftTabClick() {
  let tabEle = document.querySelectorAll(
    '.wrap .productDetail .aside .tabWrap h4'
  );
  let divEle = document.querySelectorAll(
    '.wrap .productDetail .aside .tabContent > div'
  );
  //1、选中h4标签。绑定点击事件
  tabEle.forEach(function (tabNOde, index) {
    //2、排他思想，先排除类再加
    tabNOde.onclick = function () {
      tabEle.forEach(function (item) {
        item.classList.remove('active');
      });
      this.classList.add('active');
      //3、选中每次切换所对应的内容，
      divEle.forEach(function (divNode) {
        divNode.classList.remove('active');
      });
      divEle[index].classList.add('active');
      //2、排他思想，先排除类再加
    };
  });
}

//3、底部选项卡（与2思路tongli）
function bottomTabClick() {
  let liEle = document.querySelectorAll(
    '.wrap .productDetail .detail .intro .tabWrap li'
  );
  let conEle = document.querySelectorAll(
    '.wrap .productDetail .detail .intro .tabContent > div'
  );
  liEle.forEach(function (liNode, index) {
    liNode.onclick = function () {
      liEle.forEach(function (item) {
        item.classList.remove('active');
      });
      this.classList.add('active');
      conEle.forEach(function (divNode) {
        divNode.classList.remove('active');
      });
      conEle[index].classList.add('active');
    };
  });
}

//4、左侧面板
function leftNav() {
  //1、点击class=toolBar按钮
  var toolBar = document.querySelector('.wrap .toolBar');
  var butEle = document.querySelector('.wrap .toolBar .but');
  var isClose = true;
  //2、 假设默认关闭状态（开关按钮）1
  toolBar.onclick = function () {
    if (isClose) {
      butEle.classList.replace('list', 'cross');
      toolBar.classList.replace('toolWrap', 'toolOut');
    } else {
      butEle.classList.replace('cross', 'list');
      toolBar.classList.replace('toolOut', 'toolWrap');
    }
    isClose = !isClose;
  };
}
//5、左侧悬浮离开事件
function leftLeave() {
  //1、遍历所有li
  let liEle = document.querySelectorAll('.wrap .toolBar .toolList li');

  liEle.forEach(function (liNode) {
    let iNode = liNode.querySelector('i');
    let emNode = liNode.querySelector('em');
    //当鼠标悬浮时，i- rgb(200,17,34) ;em -left :-62px
    liNode.onmouseenter = function () {
      iNode.style.backgroundColor = 'rgb(200,12,34)';
      emNode.style.left = '-62px';
    };

    //当鼠标离开时， i-rgb(122,110,110); em-left:35px')
    liNode.onmouseleave = function () {
      iNode.style.backgroundColor = 'rgb(122,110,110)';
      emNode.style.left = '35px';
    };
  });
}
//6、渲染小图和缩略图
function initSmallPic() {
  let imgSrc = goodData.imgsrc;
  let smallBox = document.querySelector(
    '.wrap .con .mainCon .previewWrap .preview .zoom'
  );
  let smallImg = document.createElement('img');
  smallImg.src = imgSrc[0].s;
  smallBox.appendChild(smallImg);

  //7、大镜下的菜单

  let listEle = document.querySelector(
    '.wrap .con .mainCon .previewWrap .specScroll .itemCon .list'
  );
  imgSrc.forEach(function (item) {
    let liEle = document.createElement('li');
    let imgEle = document.createElement('img');
    imgEle.src = item.s;
    liEle.appendChild(imgEle);
    listEle.appendChild(liEle);
  });
}

//8、给小缩略图绑定单击事件，点击li,小图片盒子出现对应的图片
let index = 0;
function thumbImgClick() {
  //遍历所有的li ,点击li,把li图片地址赋值给小图片
  let lisEle = document.querySelectorAll(
    '.wrap .con .mainCon .previewWrap .specScroll .itemCon .list li'
  );
  // console.log(lisEle)
  let smallImgBox = document.querySelector(
    '.wrap .con .mainCon .previewWrap .preview .zoom'
  );
  let smallImg = smallImgBox.firstElementChild;
  //  console.log(smallImg)

  lisEle.forEach(function (lisNode, i) {
    let imgEle = lisNode.querySelector('img');
    lisNode.onclick = function () {
      smallImg.src = lisNode.firstElementChild.src;
      index = i;
    };
  });
}

//9、给左右箭头绑定轮播效果
//1、选中箭头，然后绑定点击事件
// 2、点击时ul移动
function arrowClick() {
  let LeftBtn = document.querySelector(
    '.wrap .con .mainCon .previewWrap .specScroll .prev'
  );
  let rightBtn = document.querySelector(
    '.wrap .con .mainCon .previewWrap .specScroll .next'
  );
  let ul = document.querySelector(
    '.wrap .con .mainCon .previewWrap .specScroll .itemCon .list'
  );
  let lisEle = document.querySelectorAll(
    '.wrap .con .mainCon .previewWrap .specScroll .itemCon .list li'
  );
  // console.log(lisEle)
  //默认从第一张开始
  let ulMoveLeft = 0;
  //每点击一次移动的距离 li盒子的宽度加上右边距
  let moveStep =
    lisEle[0].offsetWidth +
    parseInt(window.getComputedStyle(lisEle[0], null).marginRight);
  // console.log(moveStep)
  //最大的移动距离
  let maxMoveLeft = (lisEle.length - 5) * moveStep;

  rightBtn.onclick = function () {
    //如果超过最大移动距离就返回
    if (ulMoveLeft === maxMoveLeft) {
      return;
    }
    ulMoveLeft += moveStep;
    ul.style.left = -ulMoveLeft + 'px';
  };
  LeftBtn.onclick = function () {
    //点击左箭头在第一张的时候截至
    if (ulMoveLeft === 0) {
      return;
    }
    ulMoveLeft -= moveStep;
    ul.style.left = -ulMoveLeft + 'px';
  };
}
//10、放大镜
function zoomGlass() {
  // 1、鼠标进入，创建遮盖盒子、大图盒子 和大图片
  let smallBox = document.querySelector(
    '.wrap .con .mainCon .previewWrap .preview .zoom'
  );
  let preview = document.querySelector(
    '.wrap .con .mainCon .previewWrap .preview'
  );
  let mask = null;
  let bigBox = null;
  let bigImg = null;
  smallBox.onmouseenter = function () {
    mask = document.createElement('div');
    mask.className = 'mask';
    smallBox.appendChild(mask);
    bigBox = document.createElement('div');
    bigBox.className = 'bigBox';
    bigImg = document.createElement('img');
    bigImg.src = goodData.imgsrc[index].b;
    bigBox.appendChild(bigImg);
    preview.appendChild(bigBox);
  };
  // 2、鼠标离开，遮盖盒子、大图盒子 和大图片消失
  smallBox.onmouseleave = function () {
    smallBox.removeChild(mask);
    preview.removeChild(bigBox);
    mask = bigBox = bigImg = null;
  };
  // 3、鼠标在小图上移动，遮盖跟随移动，遮盖在小图片盒子上移动
  smallBox.onmousemove = function (event) {
    let maskMoveLeft =
      event.clientX -
      mask.offsetWidth / 2 -
      smallBox.getBoundingClientRect().left;
    let maskMoveTop =
      event.clientY -
      mask.offsetHeight / 2 -
      smallBox.getBoundingClientRect().top;
    if (maskMoveLeft < 0) {
      maskMoveLeft = 0;
    }
    if (maskMoveTop < 0) {
      maskMoveTop = 0;
    }
    let maskMaxMoveLeft = smallBox.clientWidth - mask.offsetWidth;
    let maskMaxMoveTop = smallBox.clientHeight - mask.offsetHeight;
    if (maskMoveLeft > maskMaxMoveLeft) {
      maskMoveLeft = maskMaxMoveLeft;
    }
    if (maskMoveTop > maskMaxMoveTop) {
      maskMoveTop = maskMaxMoveTop;
    }
    mask.style.left = maskMoveLeft + 'px';
    mask.style.top = maskMoveTop + 'px';
    //大图等比例缩放
    //遮盖移动距离/遮盖移动最大距离 = 大图移动距离 /大图移动最大距离
    //大图最大移动距离 = 大图片的宽度 - 大盒子的宽度
    bigMaxLeft = bigImg.offsetWidth - bigBox.clientWidth;
    bigMaxTop = bigImg.offsetHeight - bigBox.clientHeight;
    //大图移动距离 = 遮盖移动距离*大图移动最大距离 /遮盖移动最大距离
    bigMoveLeft = (maskMoveLeft * bigMaxLeft) / maskMaxMoveLeft;
    bigMoveTop = (maskMoveLeft * bigMaxTop) / maskMaxMoveTop;
    bigImg.style.left = -bigMoveLeft + 'px';
    bigImg.style.top = -bigMoveTop + 'px';
  };
}

//11、渲染图片基本信息
function goodsBaseNews() {
  let goodsArea = document.querySelector(
    '.wrap .con .mainCon .infoWrap .choose .chooseArea'
  );
  // 1. 获取data.js中的商品的基本信息
  let goodsMessage = goodData.goodsDetail;
  // 2. 替换模板字符串中的数据
  let goodsInfo = ` <h3 class="infoName">
${goodsMessage.title}
</h3>
<p class="news">
${goodsMessage.recommend}
</p>
<div class="priceArea">
 <div class="priceArea1">
   <div class="title">
     价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格
   </div>
   <div class="price">
     <i>￥</i>
     <em>${goodsMessage.price}</em>
     <span>降价通知</span>
   </div>
   <div class="remark">
     <i>累计评价</i>
     <span>${goodsMessage.evaluateNum}</span>
   </div>
 </div>
 <div class="priceArea2">
   <div class="title">
     促&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销
   </div>
   <div class="fixWidth">
     <i>${goodsMessage.promoteSales.type}</i>
     <span>
      ${goodsMessage.promoteSales.content}
     </span>
   </div>
 </div>
</div>
<div class="support">
 <div>
   <div class="title">
     支&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;持
   </div>
   <div class="fixWidth">
   ${goodsMessage.support}
   </div>
 </div>
 <div>
   <div class="title">配&nbsp;送&nbsp;至</div>
   <div class="fixWidth">${goodsMessage.address}</div>
 </div>
</div>`;
  // 3. 上树
  let info1 = document.querySelector('.wrap .con .mainCon .infoWrap .info1');
  info1.innerHTML = goodsInfo;
}
//底部商品复选区
let priceChecked = document.querySelector(
  '.wrap .productDetail .detail .fitting .goodSuits .master p'
);
priceChecked.innerText = '￥' + goodData.goodsDetail.price;
let inputEle = document.querySelectorAll(
  '.wrap .productDetail .detail .fitting .goodSuits .suits input'
);
let goodsNum = 0;
let goodsPriceTotal = 0;
inputEle.forEach(function (input) {
  if (input.checked) {
    goodsNum++;
    goodsPriceTotal += parseInt(input.value);
  }
});
let resultTotal = document.querySelector(
  '.wrap .productDetail .detail .fitting .goodSuits .result > div .selected'
);
resultTotal.innerText = goodsNum;
let rightPriceEle = document.querySelector(
  '.wrap .productDetail .detail .fitting .goodSuits .result .price'
);
rightPriceEle.innerText = '￥' + (goodsPriceTotal + goodData.goodsDetail.price);

//12、渲染商品规格信息
function goodsSizeNews() {
  // 1. 获取data.js中的商品的规格信息
  let goodSize = goodData.goodsDetail.crumbData;
  // 2. 循环数据，创建dt节点，dl中追加dt和dd
  goodSize.forEach(function (info) {
    let dlNode = document.createElement('dl');

    let dtNode = document.createElement('dt');
    dtNode.innerText = info.title;
    dlNode.appendChild(dtNode);
    info.data.forEach(function (item) {
      let ddNode = document.createElement('dd');
      ddNode.innerText = item.type;
      //创建dd的price属性
      ddNode.setAttribute('price', item.changePrice);
      dlNode.appendChild(ddNode);
    });
    // 3. 上树
    let chooseArea = document.querySelector(
      '.wrap .con .mainCon .infoWrap .choose .chooseArea'
    );
    chooseArea.appendChild(dlNode);
  });
}

//13、商品信息点击事件
//找dl中的dd,遍历dd排他思想，当dd被点击的时候颜色变成红色

//创建一个新数组,把dl的索引中的内容存入一个对象当中,然后上树
let regionArr = [0, 0, 0, 0];
function goodsClick() {
  let dl = document.querySelectorAll(
    '.wrap .con .mainCon .infoWrap .choose .chooseArea dl'
  );
  dl.forEach(function (dlNode, dlIndex) {
    let dd = dlNode.querySelectorAll('dd');

    dd.forEach(function (ddNode) {
      ddNode.onclick = function () {
        dd.forEach(function (item) {
          item.style.color = 'rgb(102, 102, 102)';
        });
        ddNode.style.color = 'red';
        //2. 单击dd的时候，获取价格，存入条件数组中。
        regionArr[dlIndex] = {
          name: this.innerText,
          price: parseInt(this.getAttribute('price')),
        };

        let choosed = document.querySelector(
          '.wrap .con .mainCon .infoWrap .choose .chooseArea .choosed'
        );
        //清除
        choosed.innerText = '';

        regionArr.forEach(function (item, dlIndex) {
          //为假值则返回
          if (!item) {
            return;
          }
          let mark = document.createElement('mark');
          mark.innerText = item.name;
          let aNode = document.createElement('a');
          aNode.setAttribute('dlIndex', dlIndex);
          aNode.innerText = 'X';
          mark.appendChild(aNode);
          choosed.appendChild(mark);
          caculTotal();
        });
      };
    });
  });
}

//给整个choose绑定点击代理事件，当点击a标签时，移除mark
function chooseRemove() {
  let choosed = document.querySelector(
    '.wrap .con .mainCon .infoWrap .choose .chooseArea .choosed'
  );
  choosed.onclick = function (event) {
    if (event.target.localName !== 'a') {
      return;
    }
    let aNode = event.target;
    choosed.removeChild(aNode.parentElement);

    //当点击a标签的同时，给a也同时绑定dl下标，dd使用排他思想，然后默认一个dd为红色
    let dlIndex = aNode.getAttribute('dlIndex');
    //获取dl的索引
    let dl = document.querySelectorAll(
      '.wrap .con .mainCon .infoWrap .choose .chooseArea dl'
    )[dlIndex];
    let dds = dl.querySelectorAll('dd');
    dds.forEach(function (dd) {
      dd.style.color = 'rgb(102,102,102)';
    });
    dds[0].style.color = 'red';
    regionArr[dlIndex] = 0;
    caculTotal();
  };
}
// 3. 创建一个函数，实现条件数组中的规格价格和商品原价进行一个汇总即可
function caculTotal() {
  let totalPrice = document.querySelector(
    '.wrap .con .mainCon .infoWrap .info1 .priceArea .priceArea1 .price em'
  );
  let leftPrice = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .master p'
  );
  let rightTotalPrice = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .result .price'
  );
  let inputNum = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .result .selected'
  );
  let inputs = document.querySelectorAll(
    '.wrap .productDetail .detail .fitting .goodSuits .suits input'
  );
  let goodsPrice = 0;
  let regionPrice = goodData.goodsDetail.price;
  regionArr.forEach(function (item) {
    //排除假值
    if (!item) {
      return;
    }
    //被点击的商品价格累加
    goodsPrice += item.price;
  });
  let total = regionPrice + goodsPrice;
  totalPrice.innerText = total;
  leftPrice.innerText = '￥' + total;

  let inputValue = 0;
  inputs.forEach(function (input) {
    if (input.checked) {
      inputValue += parseInt(input.value);
    }
  });
  rightTotalPrice.innerText = '￥'+(inputValue +total)
}
//附加商品
function attachGoods() {
  let inputs = document.querySelectorAll(
    '.wrap .productDetail .detail .fitting .goodSuits .suits input'
  );
  let rightTotalPrice = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .result .price'
  );
  let inputNum = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .result .selected'
  );
  let leftPrice = document.querySelector(
    '.wrap .productDetail .detail .fitting .goodSuits .master p'
  );
  let attachNum = 2;
  let inputValue = 30;
  inputs.forEach(function (item) {
    item.onclick = function () {
      //在默认被点击的基础上累加
      if (item.checked) {
        attachNum++;
        inputValue += parseInt(item.value);
      } else {
        attachNum--;
        inputValue -= parseInt(item.value);
      }
      rightTotalPrice.innerText =
        '￥' + (inputValue + parseInt(leftPrice.innerText.substring(1)));
      console.log(rightTotalPrice);
      inputNum.innerText = attachNum;
    };
  });
}
